package beautiful.butterfly.server.application;


import beautiful.butterfly.server.httpserver.handlers.HttpServer;
import beautiful.butterfly.server.httpserver.handlers.IHttpServer;
import beautiful.butterfly.server.httpserver.mvc.handler.DefaultExceptionHandler;
import beautiful.butterfly.server.httpserver.mvc.handler.ExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;


/**
 * 整个系统需要各个服务器组件分开
 */
@Slf4j
public class Application {

    public static boolean developMode = true;
    public static final String CONFIG_PROPERTIES = "config.properties";
    private String path;
    private String configFilePath;
    private FileSystemXmlApplicationContext fileSystemXmlApplicationContext;
    public static final String application = "application";

    public static void setBasePackageName(String basePackageName) {
        Application.basePackageName = basePackageName;
    }

    public static String getBasePackageName() {
        return basePackageName;
    }

    private static String basePackageName = null;
    private IHttpServer httpServer = new HttpServer();

    private Environment environment = new Environment();
    private ExceptionHandler exceptionHandler = new DefaultExceptionHandler();

    public Application(String path) throws Exception {
        this.path = path;
        //
        String coreConfigPath = this.path + File.separator + CONFIG_PROPERTIES;
        Properties properties = new Properties();
        FileInputStream fileInputStream = new FileInputStream(new File(coreConfigPath));
        properties.load(fileInputStream);
        fileInputStream.close();
        this.environment.getProperties().putAll(Environment.of(properties).getProperties());
        basePackageName = (String) this.environment.get("base_package_name");
        this.configFilePath = (String) this.environment.get("config_file_path");
        this.fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext(this.configFilePath + File.separator + "beans.xml");
        this.fileSystemXmlApplicationContext.getBeanFactory().registerSingleton(application, this);
        ApplicationContextUtils.register(this, fileSystemXmlApplicationContext);
    }

    public Environment environment() {
        return environment;
    }

    public String getPath() {
        return path;
    }


    public ExceptionHandler getExceptionHandler() {
        return exceptionHandler;
    }


    public Application start() {
        try {

            httpServer.start(Application.this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }


}
